<template>
  <div class="organization-structure">
    <div
      class="page-header image"
      :style="bannerImage ? { backgroundImage: `url(${bannerImage})` } : {}"
    >
      <div class="header-overlay">
        <div class="container">
          <h1 class="page-title">{{ "组织架构" }}</h1>
          <p class="page-subtitle">
            {{ "了解展会的组织架构" }}
          </p>
        </div>
      </div>
    </div>
    <!-- 导航菜单 -->
    <div class="nav-menu">
      <div class="container">
        <nav class="about-nav">
          <a
            @click="setActiveTab('exhibition-intro')"
            :class="['nav-item', { active: activeTab === 'exhibition-intro' }]"
          >
            展会介绍
          </a>
          <a
            @click="setActiveTab('product-scope')"
            :class="['nav-item', { active: activeTab === 'product-scope' }]"
          >
            展品范围
          </a>
          <a
            @click="setActiveTab('exhibition-highlights')"
            :class="[
              'nav-item',
              { active: activeTab === 'exhibition-highlights' },
            ]"
          >
            展会集锦
          </a>
          <a
            @click="setActiveTab('venue-intro')"
            :class="['nav-item', { active: activeTab === 'venue-intro' }]"
          >
            展馆介绍
          </a>
          <a
            @click="setActiveTab('organizer-intro')"
            :class="['nav-item', { active: activeTab === 'organizer-intro' }]"
          >
            主办方介绍
          </a>
          <a
            @click="setActiveTab('organization-structure')"
            :class="[
              'nav-item',
              { active: activeTab === 'organization-structure' },
            ]"
          >
            组织架构
          </a>
          <a
            @click="setActiveTab('past-exhibitions')"
            :class="['nav-item', { active: activeTab === 'past-exhibitions' }]"
          >
            往届展会
          </a>
          <a
            @click="setActiveTab('downloads')"
            :class="['nav-item', { active: activeTab === 'downloads' }]"
          >
            下载中心
          </a>
        </nav>
      </div>
    </div>

    <div class="container">
      <section class="structure-section">
        <!-- <h2 class="section-title">{{ pageData.title || "组织架构" }}</h2> -->
        <div v-if="pageData.imageUrl" class="cover-wrapper">
          <img :src="pageData.imageUrl" class="cover-image" />
        </div>
        <div class="structure-content" v-if="organizationStructure.length">
          <div
            class="structure-item"
            v-for="(item, idx) in organizationStructure"
            :key="item.id || idx"
          >
            <div class="structure-info">
              <div
                class="structure-rich"
                v-if="item.description"
                v-html="item.description"
              ></div>
            </div>
            <div class="structure-media">
              <div class="structure-icon" v-if="!item.image">
                <el-icon
                  ><component :is="getIconComponent(item.icon)"
                /></el-icon>
              </div>
              <div class="cover-wrapper" v-else>
                <img :src="item.image" :alt="item.title" class="cover-image" />
              </div>
            </div>
          </div>
        </div>
        <div v-else class="plain-content" v-html="plainHtml"></div>
      </section>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import {
  Setting,
  User,
  Tools,
  Connection,
  Star,
} from "@element-plus/icons-vue";
import { subpageApi } from "@/api/user";

export default {
  name: "OrganizationStructure",
  setup() {
    const activeTab = ref("organization-structure");
    const pageData = ref({});
    const organizationStructure = ref([]);
    const bannerImage = ref("");
    const plainHtml = ref("");

    // 默认组织架构数据 - 仅作为API失败时的fallback
    const defaultStructure = [];

    // 获取图标组件
    const getIconComponent = (iconName) => {
      const iconMap = {
        Setting: Setting,
        User: User,
        Tools: Tools,
        Connection: Connection,
        Star: Star,
      };
      return iconMap[iconName] || Setting;
    };

    // 加载页面数据
    const loadPageData = async () => {
      try {
        // 1) 优先加载多条数据列表
        const listRes = await subpageApi.getSubpageList(
          "about",
          "organization-structure"
        );
        if (
          listRes &&
          listRes.code === "200" &&
          Array.isArray(listRes.data) &&
          listRes.data.length
        ) {
          organizationStructure.value = listRes.data.map((item, index) => {
            let parsed = {};
            try {
              parsed = item.content
                ? typeof item.content === "string"
                  ? JSON.parse(item.content)
                  : item.content
                : {};
            } catch {}
            return {
              id: item.id || index + 1,
              title: parsed.subtitle || item.title || "组织架构",
              description: parsed.content || item.content || "",
              icon: parsed.icon || "Setting",
              image: parsed.backgroundImage || item.imageUrl || "",
            };
          });
          pageData.value = {
            title: "组织架构",
            subtitle: "了解展会的组织架构",
          };
          return;
        }

        // 2) 回退到单条数据
        const response = await subpageApi.getSubpageByKey(
          "about",
          "organization-structure"
        );
        if (response && response.code === "200" && response.data) {
          const data = response.data;
          pageData.value = data;
          let itemsParsed = false;
          if (data && data.content) {
            try {
              const parsed = JSON.parse(data.content);
              if (Array.isArray(parsed)) {
                organizationStructure.value = parsed.map((it, i) => ({
                  id: it.id || i + 1,
                  title: it.title || pageData.value.title || "组织架构",
                  description: it.description || "",
                  icon: it.icon || "Setting",
                  image: it.backgroundImage || "",
                }));
                itemsParsed = true;
              } else if (parsed && parsed.content) {
                // 单对象富文本
                plainHtml.value = parsed.content;
                itemsParsed = true;
              }
            } catch (_) {
              // 非 JSON：保留为富文本/纯文本
              plainHtml.value = data.content;
            }
          }

          if (!itemsParsed && !plainHtml.value) {
            // 将纯文本内容按行拆分
            const lines = (data.content || "")
              .split(/\r?\n/)
              .map((s) => s.trim())
              .filter(Boolean);
            if (lines.length) {
              organizationStructure.value = lines.map((line, i) => ({
                id: i + 1,
                title: line.split("：")[0] || `部门 ${i + 1}`,
                description: line.includes("：")
                  ? line.slice(line.indexOf("：") + 1)
                  : line,
                icon: "Setting",
              }));
            } else {
              organizationStructure.value = defaultStructure;
            }
          }
        } else {
          organizationStructure.value = defaultStructure;
        }
      } catch (error) {
        console.error("加载组织架构数据失败:", error);
        // 使用默认数据作为回退
        organizationStructure.value = defaultStructure;
      }
    };

    const loadBanner = async () => {
      try {
        const resp = await subpageApi.getContentByType("carousel_about");
        if (
          resp &&
          resp.code === "200" &&
          Array.isArray(resp.data) &&
          resp.data.length
        ) {
          const first =
            resp.data.find((it) => it.status === "active") || resp.data[0];
          const content =
            typeof first.content === "string"
              ? JSON.parse(first.content || "{}")
              : first.content || {};
          bannerImage.value = first.imageUrl || content.image || "";
        }
      } catch (e) {
        bannerImage.value = "";
      }
    };

    const setActiveTab = (tabKey) => {
      if (!tabKey) return;
      activeTab.value = tabKey;
      // 跳转到对应的子页面
      if (tabKey !== "organization-structure") {
        window.location.href = `/${tabKey}`;
      }
    };

    onMounted(() => {
      loadPageData();
      loadBanner();
    });

    return {
      activeTab,
      pageData,
      organizationStructure,
      bannerImage,
      getIconComponent,
      plainHtml,
      setActiveTab,
    };
  },
};
</script>

<style scoped>
.organization-structure {
  min-height: 100vh;
  background: #f8f9fa;
  /* padding-top: 70px; */
}

.page-header {
  background: linear-gradient(135deg, #320063 0%, #4a0a8a 100%);
  color: white;
  padding: 80px 0;
  text-align: center;
}

.page-header.image {
  position: relative;
  background: none;
  padding: 0;
  height: 400px;
  background-size: cover;
  background-position: center;
}
.header-overlay {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.35);
  display: flex;
  align-items: center;
}

.page-title {
  font-size: 48px;
  margin-bottom: 20px;
}

.page-subtitle {
  font-size: 18px;
  opacity: 0.9;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.structure-section {
  background: white;
  border-radius: 20px;
  padding: 3rem;
  margin: 2rem 0;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.cover-wrapper {
  margin-bottom: 1.5rem;
}

.cover-image {
  width: 100%;
  height: 320px;
  object-fit: contain;
  border-radius: 12px;
  background: #f8f9fa;
}

.section-title {
  font-size: 2rem;
  color: #333;
  margin-bottom: 2rem;
  text-align: center;
}

.structure-content {
  display: grid;
  grid-template-columns: 1fr;
  gap: 2rem;
}

.plain-content {
  white-space: pre-wrap;
  color: #444;
  line-height: 1.8;
}

/* 富文本内图片限制 */
.plain-content :deep(img) {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 10px 0;
  border-radius: 8px;
}

.structure-item {
  display: flex;
  flex-direction: column;
  gap: 1.2rem;
  padding: 1.5rem;
  background: linear-gradient(135deg, #f8f9ff 0%, #e8f0ff 100%);
  border-radius: 15px;
  border: 1px solid #e0e7ff;
  transition: transform 0.3s ease;
}

.structure-item:hover {
  transform: translateY(-3px);
}

.structure-media {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.structure-icon {
  flex-shrink: 0;
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #320063 0%, #667eea 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.structure-icon .el-icon {
  font-size: 1.6rem;
  color: white;
}

.cover-wrapper {
  width: 100%;
}

.structure-info {
  width: 100%;
}

.structure-info h3 {
  font-size: 1.2rem;
  color: #320063;
  margin-bottom: 0.5rem;
  font-weight: 600;
}

.structure-info p {
  color: #666;
  line-height: 1.6;
  font-size: 0.9rem;
  margin: 0;
}

.structure-rich {
  color: #666;
  line-height: 1.7;
  white-space: normal;
  word-wrap: break-word;
  overflow-wrap: break-word;
}
.structure-rich :deep(img) {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 8px 0;
  border-radius: 6px;
}
.structure-rich :deep(p) {
  margin-bottom: 12px;
}
.structure-rich :deep(ul),
.structure-rich :deep(ol) {
  margin: 8px 0 12px 18px;
}
.structure-rich :deep(li) {
  margin: 6px 0;
  line-height: 1.6;
}
.structure-rich :deep(h1),
.structure-rich :deep(h2),
.structure-rich :deep(h3),
.structure-rich :deep(h4),
.structure-rich :deep(h5),
.structure-rich :deep(h6) {
  margin: 14px 0 8px 0;
  color: #333;
  font-weight: 600;
}

.cover-image {
  width: 100%;
  height: auto;
  max-height: 480px;
  object-fit: contain;
  border-radius: 10px;
  display: block;
}

@media (max-width: 768px) {
  .structure-section {
    padding: 2rem;
    margin: 1rem 0;
  }

  .section-title {
    font-size: 1.5rem;
  }

  .structure-content {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }
  .structure-item {
    flex-direction: column;
  }
  .structure-media,
  .structure-info {
    max-width: 100%;
    flex-basis: 100%;
  }

  .page-title {
    font-size: 2rem;
  }

  .page-subtitle {
    font-size: 1rem;
  }
}

/* 导航菜单样式 - 参考关于我们页面 */
.nav-menu {
  background: #f8f9fa;
  padding: 20px 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.about-nav {
  display: flex;
  justify-content: center;
  gap: 30px;
  flex-wrap: wrap;
}

.nav-item {
  text-decoration: none;
  color: #333;
  font-size: 1.1rem;
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 8px;
  transition: background-color 0.3s ease, color 0.3s ease;
  border: 1px solid #eee;
  cursor: pointer;
}

.nav-item:hover {
  background-color: var(--e-global-color-selected);
  color: white;
  border-color: var(--e-global-color-selected);
}

.nav-item.active {
  background-color: var(--e-global-color-selected);
  color: white;
  border-color: var(--e-global-color-selected);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .about-nav {
    gap: 15px;
  }

  .nav-item {
    font-size: 1rem;
    padding: 8px 16px;
  }
}
</style>
